package com.nm.service.impl;

import com.nm.commons.exception.SupperException;
import com.nm.commons.util.StringUtil;
import com.nm.orm.model.State;
import com.nm.orm.dao.CategoryDao;
import com.nm.orm.pojo.CategoryEntity;
import com.nm.service.CategorysService;
import com.nm.service.output.CategoryOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能说明:分类管理service
 *
 * @return <br/>
 * 修改历史：<br/>
 * 1.[2017年02月12日上午14:48] 创建方法 by hw
 */
@Service
@Transactional
@Qualifier("categorysService")
public class CategoryServiceImpl implements CategorysService {

    @Autowired
    @Qualifier("categorysDao")
    private CategoryDao cgDao;

    @Override
    public String insert(CategoryEntity categoryEntity) {
        return cgDao.insert(categoryEntity);
    }

//    @Override
//    public void insert(List<CategoryEntity> tes) {
//        cgDao.insert(tes);
//    }

    @Override
    public void saveOrUpdate(CategoryEntity categoryEntity) {
        if (StringUtil.isNull(categoryEntity.getId())) {
            categoryEntity.setCreatedAt(new Date());
        }

        if (State.DISABLE.dbValue() == categoryEntity.getState()) {
            categoryEntity.setState(State.ABLE.dbValue());
        }

        cgDao.saveOrUpdate(categoryEntity);
    }

    @Override
    public void update(CategoryEntity categoryEntity) throws SupperException {
        if (State.DISABLE.dbValue() == categoryEntity.getState()) {
            categoryEntity.setState(State.ABLE.dbValue());
        }

        cgDao.saveOrUpdate(categoryEntity);
    }

    @Override
    public CategoryEntity getById(String id) throws SupperException {
        return cgDao.findById(id);
    }

    @Override
    public void delete(CategoryEntity categoryEntity) throws SupperException {
        cgDao.delete(categoryEntity);
    }

//    @Override
//    public int deleteAll(CategoryEntity categoryEntity)
//            throws SupperException {
//        return -2;
//    }

    @Override
    public int deleteById(String id) throws SupperException {
        return cgDao.deleteById(id);
    }

    @Override
    public List<CategoryOutput> findAll() throws SupperException {
        List<CategoryEntity> categorys = cgDao.findAll();

        List<CategoryOutput> caOuts = new ArrayList<CategoryOutput>();
        CategoryOutput output = null;
        for (CategoryEntity category : categorys) {
            output = new CategoryOutput();

            output.setCategoryId(category.getId());
            output.setText(category.getDescription());
            output.setId(category.getOrderBy());

            caOuts.add(output);
        }

        return caOuts;
    }

}
